package com.lyn.utils;

import android.text.TextUtils;

/**
 * 16进制工具类
 * @author Lyn 2022/12/8
 * @version 1.0.0
 */
public class HexUtil {

    /**
     * byte[] 数组转16进制字符串
     */
    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length == 0) {
            return null;
        }
        for (byte b : src) {
            int v = b & 0xFF;
            String hv = Integer.toHexString(v).toUpperCase();
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    /**
     * hex转byte
     */
    public static byte hexToByte(String hex) {
        return (byte) Integer.parseInt(hex, 16);
    }

    /**
     * 16进制字符串转byte[]
     */
    public static byte[] hexToByteArray(String hex) {
        int hexlen = hex.length();
        byte[] result;
        if (hexlen % 2 == 1) {
            //奇数
            hexlen++;
            result = new byte[(hexlen / 2)];
            hex = "0" + hex;
        } else {
            //偶数
            result = new byte[(hexlen / 2)];
        }
        int j = 0;
        for (int i = 0; i < hexlen; i += 2) {
            result[j] = hexToByte(hex.substring(i, i + 2));
            j++;
        }
        return result;
    }


    /**
     * 16进制转字符串
     */
    private String hexToString(String hex) {
        if (TextUtils.isEmpty(hex)) return "";
        int length = hex.length();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i += 2) {
            String substring = hex.substring(i, i + 2);
            char c = (char) Integer.parseInt(substring, 16);
            sb.append(c);
        }
        return sb.toString();
    }
}

